import React, { Component } from 'react';
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import TheUpload from "@/components/TheUpload"
import { Space, Button, Modal, Form } from 'antd';
import { apiSeckillActivityPage, apiSeckillActivityFinish } from '@/request/marketingTool'
import store from "@/store/store"

export default class Kill extends Component {

    constructor(props) {
        super(props)
        this.queryFormRef = React.createRef()
        this.channelFormRef = React.createRef()
        this.state = {
            columns: [
                {
                    title: "活动ID",
                    dataIndex: "activityId",
                    key: "activityId",
                },
                {
                    title: "活动名称",
                    dataIndex: "activityName",
                    key: "activityName",
                }, {
                    title: "活动类型",
                    dataIndex: "activityType",
                    key: "activityType",
                    render(text, record) {
                        let txt = ''
                        switch (record.activityType) {
                            case 'SECKILL_HOMEPAGE':
                                txt = '首页秒杀'
                                break;
                            case 'SECKILL_ACTIVITY':
                                txt = '活动秒杀'
                                break;
                            default:
                                break;
                        }
                        return txt
                    }
                },
                {
                    title: "活动时间",
                    dataIndex: "warmingTime",
                    key: "warmingTime",
                    render: (text, record) => {
                        return record.warmingTime + '-' + record.realityEndTime
                    }
                },
                {
                    title: "秒杀开始",
                    dataIndex: "startTime",
                    key: "startTime",
                },
                {
                    title: "状态",
                    dataIndex: "activityStatus",
                    key: "activityStatus",
                },
                {
                    title: "最近修改时间",
                    dataIndex: "updateTime",
                    key: "updateTime",
                },
                {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    fixed: 'right',
                    render: (text, render) => {
                        return (
                            <div>
                                <TheButton haspermi={['market:kill:view']} onClick={() => this.onView(render)}>查看</TheButton>

                                {
                                    render.activityStatus === '已结束' ? null :
                                        <>
                                            <TheButton haspermi={['market:kill:edit']} onClick={() => this.onEdit(render)}>修改</TheButton>
                                            <TheButton haspermi={['market:kill:close']} onClick={() => this.onClose(render)}>提前结束</TheButton>
                                        </>
                                }

                            </div>
                        )
                    }
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: 0,
            code: '',
            newColumns: [],
            form_show: true,
            searchOption: [
                { field: 'key', label: '秒杀活动', placeholder: '请输入活动id/名称', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'status', label: '状态', placeholder: '请选择状态', required: false, rules: [], type: 'Select', options: [{ label: '全部', value: '', }, { label: '未开始', value: '未开始', }, { label: '进行中', value: '进行中' }, { label: '已结束', value: '已结束' }], defaultValue: '' },
            ],
            queryForm: {},
            channelModalShow: false
        }
    }
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryForm, pathName } = searchParams
        if (searchParams && pageNo && pathName == 'kill') {
            this.setState({
                queryForm,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                this.getData()
            })
        } else {
            this.getData()
        }
    }
    async getData(values) {

        const { pageNo, pageSize } = this.state.pageData
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            const params = {
                pageNo, pageSize, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'kill',
                    ...params
                }
            })
            let res = await apiSeckillActivityPage({
                pageNo, pageSize, ...this.state.queryForm
            })
            this.setState({
                dataSource: res.rows,
                total: res.totalCount
            })
        })



    }
    onAdd() {
        this.props.history.push(`/marketingTool/killAdd/null/add/null`)
    }
    onView(render) {
        console.log(render, 'render');
        this.props.history.push(`/marketingTool/killAdd/${render.activityId}/view/${render.activityType}`)
    }
    onEdit(render) {
        this.props.history.push(`/marketingTool/killAdd/${render.activityId}/edit/${render.activityType}`)
    }
    onClose(render) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "提前关闭秒杀活动可能导致正在购买的消费者无法正常下单，是否继续关闭？",
            onOk: async () => {
                apiSeckillActivityFinish({ activityId: render.activityId }).then(res => {
                    if (res.code === 0) {
                        this.pageChange(1, 10)
                    }
                })
            }
        });
    }
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: this.state.pageData.pageSize }
        }, () => {
            this.getData(values)
        })
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => this.getData())
    }
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    getFileResult = (value, key) => {
        if (value.length > 0 && value[0].hasOwnProperty('response')) {
            this.formRef.current.setFieldsValue({
                [key]: value[0].response.data
            })
        } else {
            this.formRef.current.setFieldsValue({
                [key]: ''
            })
        }
    };
    render() {
        const { channelModalShow, columns, pageData, form_show, total, searchOption, dataSource, newColumns } = this.state
        return (
            <div className="p-layout-box">
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onReset={() => this.onReset()}
                    onGetValues={(values) => this.onFormSearch(values)} >
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.getData()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton haspermi={['market:kill:add']} size="middle" onClick={() => this.onAdd()} type="primary">新增</TheButton>
                    {/* <TheButton haspermi={[]} size="middle" onClick={() => this.onChangeChannel()} type="primary">更换频道首图</TheButton> */}
                </TheTableExtend>
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={newColumns}
                    dataSource={dataSource}
                    rowKey={record => record.id}
                />
                <ThePagination pageNo={pageData.pageNo} pageSize={pageData.pageSize} total={total} pageChange={this.pageChange} />

                {/* <Modal title="更换频道首图" visible={channelModalShow} width="40%"
                    onCancel={() => this.onChannelClose()}
                    footer={null}
                >
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        ref={this.channelFormRef}
                        onFinish={(values) => this.onChannelSubmit(values)}
                    >
                        <Form.Item
                            label="频道首图"
                            name="detailImg"
                            rules={[
                                {
                                    required: true,
                                    message: '请上传频道首图!',
                                },
                            ]}
                        >
                            <TheUpload
                                isConversion={false}
                                label={"建议尺寸 700*280"}
                                getFileResult={(e) => this.getFileResult(e, 'detailImg')}
                                len={1}
                            />
                        </Form.Item>
                        <Form.Item wrapperCol={{
                            offset: 8,
                            span: 16,
                        }}>
                            <Space size="small" style={{ marginLeft: 10 }}>

                                <Button type="default" onClick={() => this.onResetChannelModal()}>
                                    重置
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    确定
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal> */}
            </div >
        );
    }
}
